package com.omronble.bp_broadcast.fragment;


import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;

import com.omron.lib.OMRONLib;
import com.omron.lib.common.OMRONBLEErrMsg;
import com.omron.lib.device.DeviceType;
import com.omron.lib.model.BPData;
import com.omronble.bp_broadcast.tools.Constants;
import com.omronble.bp_broadcast.R;
import com.omronble.bp_broadcast.tools.Utils;
import com.omronble.bp_broadcast.activity.MainActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
public class DevFragment extends DialogFragment {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.loading)
    ImageView loading;
    @BindView(R.id.llGuide4A)
    LinearLayout llGuide4A;
    @BindView(R.id.tvGuide4)
    TextView tvGuide4;
    @BindView(R.id.ivGuideB)
    ImageView ivGuideB;
    @BindView(R.id.btnGuide4)
    Button btnGuide4;
    @BindView(R.id.llGuide4B)
    LinearLayout llGuide4B;
    @BindView(R.id.btnCancel)
    Button btnCancel;
    @BindView(R.id.btnNext)
    Button btnNext;
    @BindView(R.id.layout4)
    LinearLayout layout4;
    @BindView(R.id.layout1)
    LinearLayout layout1;
    @BindView(R.id.layout2)
    LinearLayout layout2;
    @BindView(R.id.layout3)
    LinearLayout layout3;

    private int step = 1;

    public DevFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        Window window = getDialog().getWindow();
        Utils.setIsGetBpData(getContext(),false);
        OMRONLib.getInstance().StopScan();
        //去掉dialog默认的padding
        int padding = (int) (getResources().getDisplayMetrics().density * 20);
        window.getDecorView().setPadding(padding, padding, padding, padding);
        WindowManager.LayoutParams lp = window.getAttributes();
        DisplayMetrics dm = new DisplayMetrics();
        /*lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;*/
        lp.dimAmount = 0.0f;
        window.setAttributes(lp);
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        window.setLayout((int) (dm.widthPixels * 0.98), (int) (dm.heightPixels * 0.99));
        setCancelable(false);
        View view = inflater.inflate(R.layout.fragment_dev, container, false);
        ButterKnife.bind(this,view);
        return view;
    }

    @Override
    public void onDestroyView() {
        Utils.setIsGetBpData(getContext(),true);
        super.onDestroyView();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        refreshPage();
        btnCancel.setOnClickListener(view1 -> dismiss());
        btnNext.setOnClickListener(view1 -> {
            step++;
            refreshPage();
        });
    }

    private void refreshPage() {
        switch (step) {
            case 1:
                layout1.setVisibility(View.VISIBLE);
                layout2.setVisibility(View.GONE);
                layout3.setVisibility(View.GONE);
                layout4.setVisibility(View.VISIBLE);
                tvTitle.setText("请按照如下步骤操作血压仪");
                break;
            case 2:
                layout1.setVisibility(View.GONE);
                layout2.setVisibility(View.VISIBLE);
                layout3.setVisibility(View.GONE);
                layout4.setVisibility(View.VISIBLE);
                tvTitle.setText("请阅读如下流程");
                break;
            case 3:
                layout1.setVisibility(View.GONE);
                layout2.setVisibility(View.GONE);
                layout3.setVisibility(View.VISIBLE);
                llGuide4A.setVisibility(View.VISIBLE);
                startAnimation();
                llGuide4B.setVisibility(View.GONE);
                layout4.setVisibility(View.GONE);
                tvTitle.setText("提示");
                initPermission();
                break;
            case 4:
                layout1.setVisibility(View.GONE);
                layout2.setVisibility(View.GONE);
                layout3.setVisibility(View.VISIBLE);
                llGuide4A.setVisibility(View.GONE);
                llGuide4B.setVisibility(View.VISIBLE);
                stopAnimation();
                layout4.setVisibility(View.GONE);
                tvTitle.setText("提示");
                break;
        }
    }

    private void startAnimation() {
        Animation rotateAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_anim);
        LinearInterpolator lin = new LinearInterpolator();
        rotateAnimation.setInterpolator(lin);
        loading.startAnimation(rotateAnimation);
    }

    private void stopAnimation() {
        Animation animation = loading.getAnimation();
        if (animation != null)
            animation.cancel();
        llGuide4A.setVisibility(View.GONE);
        llGuide4B.setVisibility(View.VISIBLE);
    }

    /** 判断是否有SDK需要的权限，没有的话动态获取 */
    private void initPermission() {
        RxPermissions permissions = new RxPermissions(getActivity());
        permissions.setLogging(true);
        permissions.request(Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(aBoolean -> {
                    if ( aBoolean ) {
                        //权限已经都通过了，可以将程序继续打开了
                        OMRONLib omronlib = OMRONLib.getInstance();
                        DeviceType deviceType = Constants.mDeviceType;
                        omronlib.bindDevice(getActivity(), deviceType, myOmronBleCallBack);
                    } else {
                        loadFailure( "欧姆龙初始化获取权限失败" );
                    }
                });
    }

    private void loadFailure(String msg) {
        stopAnimation();
        ivGuideB.setImageDrawable(ContextCompat.getDrawable(getActivity(),R.mipmap.fail));
        tvGuide4.setText( msg );
        btnGuide4.setText( "重试" );
        btnGuide4.setOnClickListener(view -> dismiss());
    }

    /*********************************欧姆龙*************************************/
    public OMRONLib.OmronBleCallBack myOmronBleCallBack = new OMRONLib.OmronBleCallBack() {
        @Override
        public void onFailure(OMRONBLEErrMsg omronbleErrMsg) {
//            getActivity().startService(new Intent(getActivity(), XService.class));
            if ( null == getActivity() || getActivity().isFinishing() || getActivity().isDestroyed() )
                return;
            OMRONLib.getInstance().StopScan();
            Utils.setIsGetBpData(getActivity(),true);
            getActivity().runOnUiThread(() -> loadFailure( null != omronbleErrMsg ? omronbleErrMsg.getErrMsg() : "设备绑定失败" ));

        }
        @Override
        public void onBindComplete(String deviceName, String deviceId, String mac) {
//            getActivity().startService(new Intent(getActivity(), XService.class));
            if ( null == getActivity() || getActivity().isFinishing() || getActivity().isDestroyed() )
                return;
            OMRONLib.getInstance().StopScan();
            Utils.setIsGetBpData(getContext(),true);
            getActivity().runOnUiThread(() -> {
                stopAnimation();
                Toast.makeText(getActivity(), "设备绑定成功" , Toast.LENGTH_SHORT).show();
                /* BLEsmart_00000116B0495F045A76,HEM-9200T20180400128L */
                SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
                mSharedPreferences.edit()
                        .putString(Constants.deviceId,deviceId)
                        .putString(Constants.deviceName,deviceName)
                        .putString(Constants.deviceMac,mac)
                        .apply();
                /** 进入首页，关闭之前所有 */
                step++;
                refreshPage();
                btnGuide4.setOnClickListener(view -> {
                    dismiss();
                });
            });
        }


        @Override
        public void onDataReadComplete(List<BPData> list) {

        }
    };

}
